<?php
/*
* Bot to display CB user in a Google map
* Nikolai Plath - www.nik-it.de
*/

defined( '_VALID_MOS' ) or die( 'Direct Access to this script is not allowed');

$_MAMBOTS->registerFunction( 'onPrepareContent', 'botCB_Gmap' );

function botCB_Gmap( $published, &$row  )
{
	$pos = strpos($row->text, "{cbgmap");

	if ($pos === false) {
	} else {

		global $mainframe;
		global $database;
		global $my;
		
		define ( '_UE_CB_GOOGLEMAP_USER_KNOWN', 'Sie k&ouml;nnen Ihren Standort &auml;ndern, indem Sie den Marker verschieben');
		define ( '_UE_CB_GOOGLEMAP_USER_UN_KNOWN', 'Klicken Sie auf die Karte um Ihren Standort zu bestimmen' );
		define ( 'CBGMAP_SUBMIT_TITEL', 'Wenn Sie fertig sind klicken Sie bitte auf aktualisiern' );
		define ( 'CBGMAP_SUBMIT_BTN_SUBMIT', 'Aktualisieren' );
		define ( 'CBGMAP_SUBMIT_OK', 'Die &Auml;nderungen wurden gespeichert' );

		define ( '_TAB_EINS_TEXT', 'Contacto' );//ins Langfile
		define ( '_TAB_ZWEI_TEXT', 'Infos' );//ins Langfile
	
			//	$regex = "/{cbgmap=([^\s]*)\s*name=([^\s]*)}/s";
		$regex = "/{cbgmap}/s";

		//preg_match ( $regex, $row->text, $BotParams );
		//print_r ($BotParams);
		
		if ($_GET['gmapmessage'] == 'OK')
		{
			echo '<h3>' . CBGMAP_SUBMIT_OK . '</h3>';
		}

		if ($_POST['gmapcoords'] != '')
		{
			if ( $_POST['myid'] == $my->id )
			{
				$ttemp = substr($_POST['gmapcoords'],1,strlen($_POST['gmapcoords'] )-2);
				$ttemp = explode (",", $ttemp);
				
				$query = "UPDATE #__comprofiler"
				. "\n SET cb_googlemaplat = " . $ttemp[0] .", "
				. "\n cb_googlemaplng = " . $ttemp[1]
				. "\n WHERE id = " . $my->id;
				$database->setQuery( $query );
				$database->query();
//					mosRedirect ( 'index.php?option=com_comprofiler&amp;Itemid='.$Itemid.'&amp;gmapmessage=OK' );
	mosRedirect ( 'http://' . $_SERVER["HTTP_HOST"] . $_SERVER['REQUEST_URI'].'&amp;gmapmessage=OK');

			}
		}

     	$query = "SELECT id FROM #__mambots "
              ."WHERE element = 'cbgooglemap' "
              ."AND folder = 'content'";
    	$database->setQuery( $query );
	    $id = $database->loadResult();
	    $mambot = new mosMambot( $database );
	    $mambot->load( $id );
	    $botParams = new mosParameters( $mambot->params );

		$Map_Width = $botParams->get('width',"800px");
		$Map_Height = $botParams->get('height',"400px");
		$GMapKey = $botParams->get('googlekey',"NOKEY");

		$Init_Lat = $botParams->get('center_lat',"18.979025953255267");
		$Init_Lng = $botParams->get('center_lng',"-15.46875");
		$Init_Zoom = $botParams->get('zoom',"2");

//		echo "<h1>$Map_Width KEY:".$botParams->get('googlekey','NIX')."</h1>";
		
		$mainframe->addCustomHeadTag( "<script src=\"http://maps.google.com/maps?file=api&amp;v=2.76&amp;key="
			.$GMapKey
			."\" type=\"text/javascript\"></script>");

		global $database;
		$query = "SELECT * FROM #__comprofiler";
		$database->setQuery( $query );
		$users = $database->loadObjectList();

		$selectedusers = count($users);
		
//The submitform
		$fromwhere = 'http://' . $_SERVER["HTTP_HOST"] . $_SERVER['REQUEST_URI'].'&amp;Send=gesendet';
		$SendForm = '
		<h3>' . CBGMAP_SUBMIT_TITEL . '</h3>'
		
		.'<form id="form1" name="form1" method="post" action="'. $fromwhere .'">
		  <input name="gmapcoords" type="hidden" id="message2" size="40" value="" />
		  <input name="myid" type="hidden" value="'.$my->id.'" />
		  <input type="submit" name="Submit" value="' . CBGMAP_SUBMIT_BTN_SUBMIT . '" id="btn_gmapsubmit" />
		</form>
		</p>';
/////
		$EditMode = '';


		if ($selectedusers > 0)
		{
		
			$FullEditString ='';
			$cnt=0;
			foreach($users as $user)
			{
				if ($user->cb_googlemaplat)
				{
					$cnt += 1;

					if (strpos($user->avatar, "/") === false )
					{	//custom userpic
						$cbPicPath='images/comprofiler/tn';
					} else
					{	//userpic from gallery
						$cbPicPath = 'components/com_comprofiler/images/';
					}

					if ($user->avatar == '')
					{	//user has NO avatar
						$TabEinsContent = "<strong>" . $user->firstname . " " . $user->lastname . "</strong>";
					} else
					{
						$TabEinsContent = "<img src='".$cbPicPath.$user->avatar."' alt='Image' /><br /><strong>"
						.$user->firstname." ".$user->lastname
						."</strong>";
					}
					
					// user Website
					$LinkString = $user->cb_website;
					$ttemp = explode ("|*|", $user->cb_website);
					$TabZweiContent = "<strong>Website:</strong><br /><a href='http://"
					. $ttemp[0] . "' target='_blank' >" . $ttemp[1] . "</a>";

					$Markers .= "var infoTabs".$cnt." = [
					new GInfoWindowTab(\""._TAB_EINS_TEXT."\", \"".$TabEinsContent."\"),
					new GInfoWindowTab(\""._TAB_ZWEI_TEXT."\", \"".$TabZweiContent."\")
					];";
					
					$Markers .="var posn = new GLatLng(".$user->cb_googlemaplat.", ".$user->cb_googlemaplng.");";

					if ( $my->id == $user->id )
					{
						if ( $user->googlemaplat == '' )
						{
						//Known location registered user
							$EditMode = 'USER';
						}
						echo '<h3>'._UE_CB_GOOGLEMAP_USER_KNOWN.'</h3>';
						$Markers .="var marker"
							.$cnt." = new GMarker(posn, {draggable: true});";
					} else
					{
						$Markers .="var marker"
							.$cnt." = new GMarker(posn,house);";
					}
					
					$Markers .= "GEvent.addListener(marker"
						. $cnt . ", 'click', function() {
							marker" . $cnt . ".openInfoWindowTabsHtml(infoTabs" . $cnt . ");
						});
						map.addOverlay(marker".$cnt.");";
					
					if ( $my->id == $user->id )
					{
						$Markers .= "document.getElementById('message2').value = marker".$cnt.".toString();
						GEvent.addListener(marker".$cnt.", 'dragend', function()
						{
							document.getElementById('message2').value = marker".$cnt.".getPoint();
						});
						GEvent.addListener(marker".$cnt.", 'dragstart', function()
						{
							map.closeInfoWindow();
						});\n";
					}
				}
				
				// keine location. new user ?
				if ( $EditMode == '' && $my->id == $user->id )
				{
	
					echo '<h3>'._UE_CB_GOOGLEMAP_USER_UN_KNOWN.'</h3>';
	
					$EditMode = 'USER';

					$Markers .= 'var clicked;
						GEvent.addListener(map, "click", function(marker, point)
						{
							if (marker)
							{
							} else
							{
								if (clicked != 1)
								{
									clicked=1;
									var marker = new GMarker(point, {draggable: true});
									map.addOverlay(marker);
					
									document.getElementById("message2").value = point.toString();
						
									GEvent.addListener(marker, "dragend", function()
									{
										document.getElementById("message2").value = marker.getPoint();
									});
								}
							}			
					});';
				}
			}
		}			
//////////////////////GET CB END

		/************************************
		***USER INPUT
		*************************************
		*/

		//echo '<h1>'.$my->id.' - USER' .$user->id.'</h1>'; 
		$repl = '';

// The Sendform
		if ( $EditMode == 'USER' )
		{
			echo $SendForm;
		}

// The Map "Window"
		$repl .= '<div id="gmap" style="width: ' . $Map_Width . '; height: ' . $Map_Height . '"></div>';
		
// The Infobox
		$repl .= '<div id="gmap_infobox" align="left">Brought to you by:<br /><a href="http://www.nik-it.de">NiK-IT.de</a></div>';
		
		
		// me make the map ...
		$repl .= "<script type='text/javascript'>//<![CDATA[\n";
	
		// global var linked to div
		$repl .="var tst=document.getElementById('gmap');
				 var tstint;
				 ";
				 
		// Functions to watch if the map has changed
		$repl .= "function checkMap()
			{
				if (GBrowserIsCompatible())
				{
					if (tst)
						if (tst.offsetWidth != tst.getAttribute(\"oldValue\"))
						{
							tst.setAttribute(\"oldValue\",tst.offsetWidth);

							if (tst.getAttribute(\"refreshMap\")==0)
							if (tst.offsetWidth > 0) {
								clearInterval(tstint);
								getMap();
								tst.setAttribute(\"refreshMap\", 1);
							} 
						}
				}
			}";


		// Function for displaying the map and marker
		$repl .= "function getMap()
			{
				if (tst.offsetWidth > 0) {
				var map = new GMap2(document.getElementById('gmap'));
					";

		//The icon	
		$repl .= "
		var baseIcon = new GIcon();
          baseIcon.iconSize=new GSize(32,32);
          baseIcon.shadowSize=new GSize(56,32);
          baseIcon.iconAnchor=new GPoint(16,32);
          baseIcon.infoWindowAnchor=new GPoint(16,0);
          
	   	var house = new GIcon(baseIcon, 'http://maps.google.com/mapfiles/kml/pal3/icon56.png', null, 'http://maps.google.com/mapfiles/kml/pal3/icon56s.png');
	  	  ";
	   	$repl .= "var kreutz = new GIcon(baseIcon, 'http://maps.google.com/mapfiles/kml/pal3/icon46.png', null, 'http://maps.google.com/mapfiles/kml/pal3/icon46s.png');
	  	  ";

	//the controls
		$repl .= "map.addControl(new GLargeMapControl());
				map.addControl(new GMapTypeControl());
				map.addControl(new GOverviewMapControl());
				map.addControl(new GScaleControl());";

	//set the center
		$repl .= "map.setCenter(new GLatLng(" . $Init_Lat . ", " .$Init_Lng . ")," . $Init_Zoom . ");";
	
	//InfoBox
	$InfoBox = "var pos = new GControlPosition(G_ANCHOR_BOTTOM_LEFT, new GSize(2,30));
      pos.apply(document.getElementById('gmap_infobox'));
      map.getContainer().appendChild(document.getElementById('gmap_infobox'));";

	$repl .= $InfoBox;
	
	$repl .= $Markers;	

	$repl .= "}
		}
		//]]></script>
		";

////Here comes the mysterious Timeoutcode for FCKNG IE #*+-
		// Call the Maps through timeout to render in IE also
		// Set an event for watching the changing of the map so it can refresh itself
	
	$repl .= "<script type=\"text/javascript\">//<![CDATA[\n";
			
	$repl .="if (GBrowserIsCompatible()) {
				tst.setAttribute(\"oldValue\",0);
				tst.setAttribute(\"refreshMap\",0);
				tstint=setInterval(\"checkMap()\",500);
			}
		//]]></script>
		";

     $row->text = preg_replace($regex, $repl, $row->text);
     return true;
  }
}  
?>
